<?php
/**
 * Fastapp.
 * 3/7/24
 * @Author deepsea
 * @Contact telegram:deepsea159
 */

namespace App\Fastapp\Api\Service\Cms;


use App\Fastapp\Model\FastappArticle;
use App\Fastapp\Model\FastappCategory;
use App\Fastapp\Model\FastappCategoryArticle;

class ArticleService
{
    public function list(int|string $code): array
    {
        if (is_numeric($code)) $map['category_id'] = $code;
        else $map['category_id'] = FastappCategory::query()->where('code', $code)->value('id');
        $ids = FastappCategoryArticle::query()->where($map)->pluck('article_id');
        $paginate = FastappArticle::query()
            ->select(['id', 'title', 'cover', 'video', 'brief'])
            ->orderByDesc('sort')->orderByDesc('id')
            ->whereIn('id', $ids)->simplePaginate();
        $list = [];
        foreach ($paginate->items() as $item) {
            $v = $item->toArray();
            $v['title'] = fastapp_lang_text($item->title);
            $v['subtitle'] = fastapp_lang_text($item->subtitle);
            $v['cover'] = fastapp_lang_text($item->cover);
            $v['video'] = fastapp_lang_text($item->video);
            $v['brief'] = fastapp_lang_text($item->brief);
            $list[] = $v;
        }
        return ['list' => $list];
    }

    public function detail(int|string $code): array
    {
        if (is_numeric($code)) {
            $map = ['id' => $code];
        } else {
            $map['code'] = $code;
        }
        $md = FastappArticle::query()->where($map)->firstOrFail();
        $md->title = fastapp_lang_text($md->title);
        $md->subtitle = fastapp_lang_text($md->subtitle);
        $md->cover = fastapp_lang_text($md->cover);
        $md->video = fastapp_lang_text($md->video);
        $md->brief = fastapp_lang_text($md->brief);
        $md->content = fastapp_lang_text($md->content);
        return $md->toArray();
    }

    public function notice(): array
    {
        $account_type = fastapp_header('account-type');
        $category_id = FastappCategory::query()->where(['code' => $account_type])->value('id');
        $article_id = FastappCategoryArticle::query()->where(['category_id' => $category_id])->pluck('article_id')->toArray();
        $list = FastappArticle::query()->whereIn('id', $article_id)->orderByDesc('id')
            ->get(['title', 'subtitle', 'brief'])->map(function ($item) {
                $item->title = fastapp_lang_text($item->title);
                $item->subtitle = fastapp_lang_text($item->subtitle);
                $item->brief = fastapp_lang_text($item->brief);
                return $item;
            });
        return ['list' => $list];
    }
}